<template>
  <BasicModal v-bind="config" @register="registerModal" :title="currTitle" wrapClassName="loginSelectModal" v-model:open="open">
    <a-form ref="formRef" :model="formState" :rules="rules" v-bind="layout" :colon="false" class="loginSelectForm">
      <!--多租户选择-->
      <a-form-item v-if="isMultiTenant" name="id" :validate-status="validate_status">
        <!--label内容-->
        <template #label>
          <a-tooltip placement="topLeft">
            <template #title>
              <span>请选择登录的租户</span>
            </template>
            <a-avatar style="background-color: #87d068" :size="30"> 租户 </a-avatar>
          </a-tooltip>
        </template>
        <template #extra v-if="validate_status == 'error'">
          <span style="color: #ed6f6f">请选择登录租户</span>
        </template>
        <!--租户下拉内容-->
        <a-select
          showSearch
          v-model:value="formState.tenantId"
          @change="handleTenantChange"
          placeholder="请选择登录租户"
          :class="{ 'valid-error': validate_status == 'error' }"
        >
          <template v-for="(tenant, index) in tenantList" :key="tenant.id">
            <a-select-option :value="tenant.id">
              {{ tenant.name }} 
              <a-tag v-if="tenant.tenantTypeName" color="green">{{ tenant.tenantTypeName }}</a-tag> 
              <span v-if="index === 0" class="preSelectTenant">上次登录</span>
            </a-select-option>
          </template>
        </a-select>
      </a-form-item>
    </a-form>

    <template #footer>
      <a-button @click="handleSubmit" type="primary" :loading="loading">确认</a-button>
    </template>
  </BasicModal>
</template>

<script lang="ts">
  import { defineComponent, ref, computed, onMounted, unref, reactive, UnwrapRef } from 'vue';
  import { Avatar, Tag } from 'ant-design-vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useUserStore } from '/@/store/modules/user';
  import { listTenant, selectLoginTenant } from '/@/api/sys/user';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { getUserInfo } from '/@/api/sys/user';
  import { getTenantId } from '/@/utils/tenant'
  const { t } = useI18n();
  interface FormState {
    orgCode: string | undefined;
    tenantId: number | string;
  }
  export default defineComponent({
    name: 'loginSelect',
    components: {
      Avatar,
      BasicModal,
    },
    emits: ['success', 'register'],
    setup(props, { emit }) {
      const userStore = useUserStore();
      const { notification, createMessage } = useMessage();
      //租户配置
      const isMultiTenant = ref(false);
      const tenantList = ref([]);
      const validate_status = ref('');
      //弹窗显隐
      const open = ref(false);
      //表单
      const formRef = ref();
      const loading = ref(false)

      //选择的租户
      const formState: UnwrapRef<FormState> = reactive({
        orgCode: undefined,
        tenantId: null,
      });

      const config = {
        maskClosable: false,
        closable: false,
        canFullscreen: false,
        width: '500px',
        minHeight: 20,
        maxHeight: 20,
      };
      //弹窗操作
      const [registerModal, { closeModal }] = useModalInner();

      //当前标题
      const currTitle = computed(() => {
        if (unref(isMultiTenant)) {
          return '请选择您要登录的企业';
        }
      });

      const rules = ref({
        tenantId: [{ required: unref(isMultiTenant), type: 'number', message: '请选择您要登录的企业', trigger: 'change' }],
      });

      const layout = {
        labelCol: { span: 4 },
        wrapperCol: { span: 18 },
      };
      /**
       * 处理租户情况
       */
      async function bizTenantList() {
        // 无论是不是一个租户都让用户选择登录
        isMultiTenant.value = true;
        tenantList.value = await listTenant()
        if (Array.isArray(tenantList.value)) {
          if (tenantList.value.length >= 1) {
            formState.tenantId = tenantList.value[0].id;
            return true
          }
        }
        return false
      }

      const loginSelectOk = ({ user, tenant }) => {
        console.log('登录成功 ', user);
        try {
          if (user) {
            setTimeout(() => {
              notification.success({
                message: t('sys.login.loginSuccessTitle'),
                description: `${t('sys.login.loginSuccessDesc')}: ${user.realName}`,
                duration: 3,
              });
            }, 2000)
            userStore.afterLoginAction(true, { tenantId: tenant.id })
          }
        } finally {
         
        }
      }

      /**
       * 确认选中的租户信息
       */
      async function handleSubmit() {
        try {
          //
          createMessage.loading({
            content: t('sys.app.menuLoading'),
            key: 'menu_loading'
          });
          loading.value = true
          formRef.value?.validate()
          // 调用确认授权接口
          const tenantInfo = await selectLoginTenant({
            tenantId: formState.tenantId, 
            loginId: userStore.getAuthInfo.loginId
          })
          await userStore.switchTenant(formState.tenantId as string, true)
          loginSelectOk({ tenant: tenantInfo, user: userStore.getUserInfo })
        } catch(e) {
          console.error('error', e);
        } finally {
          loading.value = false
          setTimeout(() => createMessage.destroy('menu_loading'), 500)
        }
      }
     
      /**
       * 请求失败处理
       */
      function requestFailed(err) {
        notification.error({
          message: '登录失败',
          description: ((err.response || {}).data || {}).message || err.message || '请求出现错误，请稍后再试',
          duration: 4,
        });
      }

      /**
       * 关闭model
       */
      function close() {
        closeModal();
        reset();
      }

      /**
       * 弹窗打开前处理
       */
      async function show() {
        const userInfo = userStore.getUserInfo
        await reset();
        const ret = await bizTenantList();
        if (!ret) {
          notification.error({
            message: t('sys.api.errorTip'),
            description: '您尚未加入任何企业',
            duration: 3,
          });
          return
        }
        if (!unref(isMultiTenant)) {
          // TODO 有问题
          emit('success', { tenantId: '-1', ...userInfo });
        } else {
          open.value = true;
        }
      }

      /**
       *重置数据
       */
      function reset() {
        tenantList.value = [];
        validate_status.value = '';

      }

      function handleTenantChange(e) {
        validate_status.value = '';
      }

      onMounted(() => {
        if (userStore.getAuthInfo.accessToken && !userStore.getSelectTenant.id) {
          console.log('触发自动选择企业/手动选择')
          const authInfo = userStore.getAuthInfo
          show({
            accessToken: authInfo.accessToken,
            loginId: authInfo.loginId,
          })
        }
      })

      return {
        registerModal,
        open,
        tenantList,
        isMultiTenant,
        validate_status,
        formState,
        rules,
        layout,
        formRef,
        currTitle,
        config,
        loading,
        handleTenantChange,
        show,
        handleSubmit,
      };
    },
  });
</script>

<style lang="less" scoped>
  .loginSelectForm {
    margin-bottom: -20px;
  }

  .loginSelectModal {
    top: 10px;
  }

  .preSelectTenant {
    color: #0089ff;
    font-size: 12px;
    align-self: center;
  }
</style>
